<template>
  <div class="login-container">
    <el-form :model="loginForm" class="login-form">
      <el-form-item label="用户名">
        <el-input v-model="loginForm.id" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item label="密码">
        <el-input type="password" v-model="loginForm.password" placeholder="请输入密码"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleLogin">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { login } from "@/api/user"

const router = useRouter()

const loginForm = ref({
  id: '',
  password: ''
})

const handleLogin = async () => {
  try {
    const response = await login(loginForm.value)
    if (response.code === 200) {
      ElMessage.success('登录成功')
      localStorage.setItem('token', response.data.token)
      router.push('/')
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    ElMessage.error('登录失败，请稍后再试')
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 100px;
}

.login-form {
  width: 300px;
}
</style>
